package cn.sc.summer.seata.service;

import cn.sc.summer.redis.util.NacosService;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import io.seata.spring.boot.autoconfigure.properties.SeataProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 接口：seata配置类
 *
 * @author a-xin
 * @date 2024/5/22 17:01
 */
@Slf4j
@Component
public class SeataService {

    /**
     * 新增seata配置项，事务组nacos配置文件
     *
     * @param seataProperties       seata配置文件
     * @param nacosConfigProperties nacos配置文件
     * @return 是否创建成功
     */
    public static Boolean creatSeataConfig(SeataProperties seataProperties, NacosConfigProperties nacosConfigProperties) throws NacosException {
        //"txServiceGroup":"product-server-group"
        String txServiceGroup = "service.vgroupMapping." + seataProperties.getTxServiceGroup();
        //group='PROJECT_GROUP'
        String group = nacosConfigProperties.getGroup();
        ConfigService configService = NacosService.getConfigService(nacosConfigProperties);
        configService.removeConfig(txServiceGroup, group);
        configService.publishConfig(txServiceGroup, group, nacosConfigProperties.getClusterName(), ConfigType.TEXT.getType());
        return Boolean.TRUE;
    }

    /**
     * 删除seata事务组配置文件
     *
     * @param seataProperties       seata配置文件
     * @param nacosConfigProperties nacos配置文件
     * @return 是否删除成功
     */
    public static Boolean deleteSeataConfig(SeataProperties seataProperties, NacosConfigProperties nacosConfigProperties) throws NacosException {
        String txServiceGroup = "service.vgroupMapping." + seataProperties.getTxServiceGroup();
        //group='PROJECT_GROUP'
        String group = nacosConfigProperties.getGroup();
        ConfigService configService = NacosService.getConfigService(nacosConfigProperties);
        configService.removeConfig(txServiceGroup, group);
        return Boolean.TRUE;
    }

}
